package com.xnyzc.lhy.didi.service.impl.operation;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xnyzc.lhy.common.component.didi.DiDiUrlConstant;
import com.xnyzc.lhy.common.component.redis.RedisCommon;
import com.xnyzc.lhy.common.constant.MessageConstant;
import com.xnyzc.lhy.common.constant.RedisPrefixConstant;
import com.xnyzc.lhy.common.entity.DiDiRv;
import com.xnyzc.lhy.common.entity.ParameterEnum;
import com.xnyzc.lhy.common.entity.Qw;
import com.xnyzc.lhy.common.exception.DiDiException;
import com.xnyzc.lhy.common.penum.EDiDiErrorCode;
import com.xnyzc.lhy.common.penum.EOrderType;
import com.xnyzc.lhy.common.penum.order.EBillType;
import com.xnyzc.lhy.common.penum.order.ECancelOrderType;
import com.xnyzc.lhy.common.penum.order.EDiDiOrderStatus;
import com.xnyzc.lhy.common.penum.order.EOrderOtherPrice;
import com.xnyzc.lhy.common.penum.order.EOrderStatus;
import com.xnyzc.lhy.common.penum.order.EUpdateOrderFeeType;
import com.xnyzc.lhy.common.penum.order.EUpdateOrderType;
import com.xnyzc.lhy.common.util.CheckUtil;
import com.xnyzc.lhy.common.util.IDUtil;
import com.xnyzc.lhy.common.util.RequestMethodUtil;
import com.xnyzc.lhy.common.util.TokenUtil;
import com.xnyzc.lhy.common.util.retry.RetryUtil;
import com.xnyzc.lhy.common.util.sign.AttestationTool;
import com.xnyzc.lhy.didi.common.constants.BillConstant;
import com.xnyzc.lhy.didi.entity.order.InitiatePaymentParam;
import com.xnyzc.lhy.didi.entity.order.OaCOrderPersonal;
import com.xnyzc.lhy.didi.entity.order.OaOrderFeeRecord;
import com.xnyzc.lhy.didi.entity.param.operation.BillRefundParam;
import com.xnyzc.lhy.didi.entity.param.operation.CloseOrderParam;
import com.xnyzc.lhy.didi.entity.param.operation.FreeChargeParam;
import com.xnyzc.lhy.didi.entity.param.order.OrderArrivalsParam;
import com.xnyzc.lhy.didi.entity.param.order.OrderDetailParam;
import com.xnyzc.lhy.didi.entity.param.synchronization.ChangePriceParam;
import com.xnyzc.lhy.didi.entity.param.synchronization.PassengerBill;
import com.xnyzc.lhy.didi.entity.price.OaSysBillRules;
import com.xnyzc.lhy.didi.entity.results.didi.operation.CloseOrderResults;
import com.xnyzc.lhy.didi.entity.results.didi.operation.QueryRefundResults;
import com.xnyzc.lhy.didi.entity.results.didi.order.OrderStatusResults;
import com.xnyzc.lhy.didi.feign.amap.IAmapService;
import com.xnyzc.lhy.didi.feign.finance.IOaDFreezeService;
import com.xnyzc.lhy.didi.feign.message.FeignMessageService;
import com.xnyzc.lhy.didi.feign.mq.IMqService;
import com.xnyzc.lhy.didi.mapper.order.OaCOrderPersonalMapper;
import com.xnyzc.lhy.didi.mapper.order.OaDOrderMapper;
import com.xnyzc.lhy.didi.mapper.order.OaOrderFeeRecordMapper;
import com.xnyzc.lhy.didi.mapper.price.OaSysBillRulesMapper;
import com.xnyzc.lhy.didi.mq.MQProducer;
import com.xnyzc.lhy.didi.service.operation.CustomerServiceOperationService;
import com.xnyzc.lhy.didi.service.order.OrderCorrelationService;
import com.xnyzc.lhy.didi.service.other.IOaDUserInfoService;
import com.xnyzc.lhy.didi.util.OrderUtil;
import com.xnyzc.lhy.finance.entity.bill.OaDBill;
import com.xnyzc.lhy.order.entity.gps.OaDVehicleGps;
import com.xnyzc.lhy.order.entity.order.OaDOrder;
import com.xnyzc.lhy.order.entity.order.OaOrderOtherPrice;
import com.xnyzc.lhy.order.entity.user.OaDUserInfo;
import com.xnyzc.lhy.order.entity.user.message.OaSysMessage;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 客服操作相关
 * </p>
 *
 * @author zhengxu
 * @since 2019-10-06
 */
@Service
@Slf4j
public class CustomerServiceOperationServiceImpl implements CustomerServiceOperationService {
    @Autowired
    private OaCOrderPersonalMapper oaCOrderPersonalMapper;

    @Autowired
    private OaDOrderMapper oaDOrderMapper;

    @Autowired
    private MQProducer mqProducer;

    @Autowired
    private IMqService iMqService;

    @Autowired
    private IAmapService iAmapService;

    @Autowired
    private RedisCommon redisCommon;

    @Autowired
    private OaOrderFeeRecordMapper oaOrderFeeRecordMapper;

    @Autowired
    private OaSysBillRulesMapper billRulesMapper;

    @Autowired
    private IOaDFreezeService oaDFreezeService;

    @Autowired
    private FeignMessageService feignMessageService;

    @Autowired
    private OrderCorrelationService orderCorrelationService;

    @Autowired
    private IOaDUserInfoService dUserInfoService;

    /**
     * 客服取消订单
     * <p>
     * 暂时不使用
     *
     * @param param 入参实体
     * @return
     */
    @Override
    public DiDiRv getCancelOrder(CloseOrderParam param) {
        CloseOrderResults results = new CloseOrderResults();

        if (StringUtils.isBlank(param.getOrder_id())) {
            return DiDiRv.wrap(EDiDiErrorCode.parameterError, results);
        }

        // 查找订单
        OaCOrderPersonal oaCOrderPersonal = iMqService.billDetails(param.getOrder_id());

        // 滴滴状态
        String orderStatus = oaCOrderPersonal.getDidiOrderStatus().toString();

        //  判断订单状态
        if (!StringUtils.equals(orderStatus, "101") && !StringUtils.equals(orderStatus, "102")) {
            throw DiDiException.create(EDiDiErrorCode.cancelOrderStatusError);
        }

        // 判断司机是否在线
        String str = redisCommon.getStr(RedisPrefixConstant.GPS_VEH_KEY_PREFIX + oaCOrderPersonal.getDriverId());
        if (CheckUtil.strIsEmpty(str)) {
            throw DiDiException.create(EDiDiErrorCode.driverNotOnline);
        }

        param.setOrder_status(orderStatus);
        param.setOpen_oid(oaCOrderPersonal.getDidiOrderId());

        //调用didi接口，直接接关闭订单
        String data = this.closeDidiOrder(param);

        if (CheckUtil.strIsEmpty(data)) {
            throw DiDiException.create(EDiDiErrorCode.httpRequestDidiUrlError);
        }
        JSONObject jsonObject = JSONObject.parseObject(data);

        if (jsonObject.get(DiDiUrlConstant.ERRNO).equals(EDiDiErrorCode.success.getValue())) {
            log.info("调用滴滴取消订单服务成功");

            // 成功
            JSONObject dataObject = jsonObject.getJSONObject("data");
            results.setOrder_status(dataObject.getString("order_status"));
            // 修改订单状态
            EDiDiOrderStatus byId = EDiDiOrderStatus.findByDidiType(Integer.valueOf(results.getOrder_status()));

            Integer dOrderStatus = -1;

            // 判断返回状态108直接关单
            String orderNo = param.getOrder_id();
            if (StringUtils.equals(results.getOrder_status(), EDiDiOrderStatus.serviceClose.getDidiType().toString())) {
                // 删除redis 释放司机状态
                String key = RedisPrefixConstant.ORDER_OA_D_ORDER + orderNo;
                String keyVeh = RedisPrefixConstant.ORDER_VEH_TEMPORARY_STORAGE + orderNo;
                redisCommon.remove(keyVeh);
                redisCommon.remove(key);

                dOrderStatus = byId.getType();
            }
            Date date = new Date();

            // 修改订单表
            this.cancelUpdateOaCOrderPersonal(oaCOrderPersonal, date, orderNo, byId.getType(), byId.getDidiType());

            // 修改司机订单表
            this.cancelUpdateDOrder(date, orderNo, dOrderStatus);

            return DiDiRv.wrap(EDiDiErrorCode.success, results);
        } else {
            log.info("调用滴滴取消订单服务失败");
        }

        try {
            return JSONObject.parseObject(data, DiDiRv.class);
        } catch (Exception e) {
            throw DiDiException.create(EDiDiErrorCode.DiDiGrabServerError);
        }
    }

    /**
     * 客服关单（通知司机关单）
     *
     * @param param 入参实体
     * @return
     */
    @Override
    public DiDiRv getCloseOrder(CloseOrderParam param) {
        CloseOrderResults results = new CloseOrderResults();
        if (StringUtils.isBlank(param.getOrder_id())) {
            return DiDiRv.wrap(EDiDiErrorCode.parameterError, results);
        }
        String orderNo = param.getOrder_id();
        log.info("开始客服关单，订单号为{}", orderNo);
        // 查找订单,客服只需要输入第三方订单号即可
        OaCOrderPersonal oaCOrderPersonal = iMqService.billDetails(orderNo);
        String orderStatus = oaCOrderPersonal.getDidiOrderStatus().toString();
        param.setOrder_status(orderStatus);
        param.setOpen_oid(oaCOrderPersonal.getDidiOrderId());
        // 如果为101,102则直接关单
        if (!StringUtils.equals(orderStatus, "101") && !StringUtils.equals(orderStatus, "102") && !StringUtils.equals(orderStatus, "103") && !StringUtils.equals(orderStatus, "104")) {
            throw DiDiException.create(EDiDiErrorCode.closeOrderParamsError);
        }
        // 判断司机是否在线
        String str = redisCommon.getStr(RedisPrefixConstant.GPS_VEH_KEY_PREFIX + oaCOrderPersonal.getDriverId());
        if (CheckUtil.strIsEmpty(str)) {
            log.error(EDiDiErrorCode.driverNotOnline.toChString());
        }
        OaDVehicleGps oaDVehicleGps = null;
        if (CheckUtil.strIsNotEmpty(str)) {
            oaDVehicleGps = JSON.parseObject(str, OaDVehicleGps.class);
        }
        // 查询乘客订单状态，如果乘客状态为106
        OrderDetailParam orderDetailParam = new OrderDetailParam();
        orderDetailParam.setOrder_id(orderNo);
        orderDetailParam.setOpen_oid(oaCOrderPersonal.getDidiOrderId());
        DiDiRv orderStatusDiDi = orderCorrelationService.getOrderStatus(orderDetailParam);
        OrderStatusResults orderStatusResults = (OrderStatusResults) orderStatusDiDi.getData();
        Date date = new Date();
        if (StringUtils.equals(orderStatusResults.getStatus(), "106")) {
            // 修改订单表
            UpdateWrapper<OaCOrderPersonal> updateWrapperPre = new UpdateWrapper<>();
            updateWrapperPre.set(OaCOrderPersonal.ORDER_STATUS, EDiDiOrderStatus.cancelOrderNoNeedPayment.getType());
            updateWrapperPre.set(OaCOrderPersonal.DIDI_ORDER_STATUS, EDiDiOrderStatus.cancelOrderNoNeedPayment.getDidiType());
            updateWrapperPre.set(OaCOrderPersonal.UPDATE_TIME, date);
            updateWrapperPre.set(OaCOrderPersonal.CANCEL_ORDER_TIME, date);
            updateWrapperPre.set(OaCOrderPersonal.CANCEL_REASON, ECancelOrderType.replyPassengersAfter.getType());
            updateWrapperPre.eq(OaCOrderPersonal.ORDER_NO, orderNo);
            int updateNum = oaCOrderPersonalMapper.update(null, updateWrapperPre);
            if (updateNum < 0) {
                throw DiDiException.create(EDiDiErrorCode.updateOrderInfoFail);
            }
            // 修改司机接单表
            UpdateWrapper<OaDOrder> dOrderUpdatePre = new UpdateWrapper<>();
            dOrderUpdatePre.set(OaDOrder.ORDER_STATUS, EDiDiOrderStatus.cancelOrderNoNeedPayment.getType());
            dOrderUpdatePre.set(OaDOrder.UPDATE_TIME, date);
            dOrderUpdatePre.eq(OaDOrder.ORDER_NO, orderNo);
            int dUpdate = oaDOrderMapper.update(null, dOrderUpdatePre);
            if (dUpdate < 1) {
                throw DiDiException.create(EDiDiErrorCode.dOrderUpdateFail);
            }
            QueryWrapper<OaDUserInfo> dUserWrapperPre = new QueryWrapper<>();
            dUserWrapperPre.select(OaDUserInfo.CURRENT_ORDER_NO);
            dUserWrapperPre.eq(OaDUserInfo.DRIVER_ID, oaCOrderPersonal.getDriverId());
            OaDUserInfo one = dUserInfoService.getOne(dUserWrapperPre);
            if (StringUtils.equals(one.getCurrentOrderNo(), orderNo)) {
                // 释放司机运力
                iMqService.driverUnlock(oaCOrderPersonal.getDriverId().toString());
            }
            return DiDiRv.wrapSuccess(new Object());
        }
        if (StringUtils.equals(orderStatus, "101") || StringUtils.equals(orderStatus, "102") || StringUtils.equals(orderStatus, "104")) {
            boolean isTrue = false;
            if (StringUtils.equals(orderStatus, "104")) {
                if (!StringUtils.equals(orderStatusResults.getStatus(), "103")) {
                    log.info("当前滴滴方状态不允许关闭订单，时空状态为：{}，滴滴状态为：{}", orderStatus, orderStatusResults.getStatus());
                    return DiDiRv.wrap(EDiDiErrorCode.closeOrderDiDiStatusError, orderStatusResults.getStatus());
                }
                // 则进行客服103关单
                log.info("客服104状态关单，时空状态为：{}，滴滴状态为：{}", orderStatus, orderStatusResults.getStatus());
                param.setOrder_status(EDiDiOrderStatus.duringTrip.getDidiType().toString());
                isTrue = true;
            }
            String url = DiDiUrlConstant.didiUrl + DiDiUrlConstant.CLOSE_ORDER_API;
            param.setApp_id(DiDiUrlConstant.didiAppId);
            param.setSign(DiDiUrlConstant.didiSignPro);
            String timestamp = String.valueOf(date.getTime() / 1000);
            param.setTimestamp(timestamp);
            String signParameter = AttestationTool.getSign(param, DiDiUrlConstant.X_WWW_FORM_URLENCODED);
            String data = null;
            try {
                data = RetryUtil.retryRequestMethodUtil(signParameter, url, null, null, null);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (CheckUtil.strIsEmpty(data)) {
                throw DiDiException.create(EDiDiErrorCode.httpRequestDidiUrlError);
            }
            JSONObject jsonObject = JSONObject.parseObject(data);
            if (jsonObject.get(DiDiUrlConstant.ERRNO).equals(EDiDiErrorCode.success.getValue())) {
                log.info("客服关单调用滴滴接口成功！！！订单号为：{}", orderNo);
                // 成功
                JSONObject dataObject = jsonObject.getJSONObject("data");
                results.setOrder_status(dataObject.getString("order_status"));
                // 104状态关单
                if (isTrue) {
                    log.info("客服104关单成功，这里截止！！");
                    return DiDiRv.wrap(EDiDiErrorCode.success, results);
                }
                // 修改订单状态
                EDiDiOrderStatus byId = EDiDiOrderStatus.findByDidiType(Integer.valueOf(results.getOrder_status()));
                /* ############ 判断返回状态108直接关单，104更改司机状态进入发起收款界面 */
                if (StringUtils.equals(results.getOrder_status(), EDiDiOrderStatus.serviceClose.getDidiType().toString())) {
                    log.info("客服关单，滴滴返回状态为108，订单号为：{}", orderNo);
                    // 修改订单表
                    UpdateWrapper<OaCOrderPersonal> updateWrapper = new UpdateWrapper<>();
                    updateWrapper.set(OaCOrderPersonal.ORDER_STATUS, byId.getType());
                    updateWrapper.set(OaCOrderPersonal.DIDI_ORDER_STATUS, byId.getDidiType());
                    updateWrapper.set(OaCOrderPersonal.UPDATE_TIME, date);
                    updateWrapper.set(OaCOrderPersonal.CANCEL_ORDER_TIME, date);
                    updateWrapper.set(OaCOrderPersonal.CANCEL_REASON, ECancelOrderType.replyServiceAfter.getType());
                    updateWrapper.eq(OaCOrderPersonal.ORDER_NO, orderNo);
                    // 修改司机接单表
                    UpdateWrapper<OaDOrder> dOrderUpdate = new UpdateWrapper<>();
                    int updateNum = oaCOrderPersonalMapper.update(null, updateWrapper);
                    if (updateNum < 0) {
                        throw DiDiException.create(EDiDiErrorCode.updateOrderInfoFail);
                    }
                    // 删除redis
                    String key = RedisPrefixConstant.ORDER_OA_D_ORDER + orderNo;
                    String keyVeh = RedisPrefixConstant.ORDER_VEH_TEMPORARY_STORAGE + orderNo;
                    redisCommon.remove(keyVeh);
                    redisCommon.remove(key);
                    // 修改司机接单表状态
                    QueryWrapper<OaDOrder> dOrderQuery = new QueryWrapper<>();
                    dOrderQuery.select(OaDOrder.VERSION);
                    dOrderQuery.eq(OaDOrder.ORDER_NO, orderNo);
                    List<OaDOrder> oaDOrders = oaDOrderMapper.selectList(dOrderQuery);
                    if (CheckUtil.collectionIsEmpty(oaDOrders)) {
                        throw DiDiException.create(EDiDiErrorCode.dOrderSelectFail);
                    }
                    dOrderUpdate.set(OaDOrder.ORDER_STATUS, byId.getType());
                    dOrderUpdate.set(OaDOrder.UPDATE_TIME, date);
                    dOrderUpdate.set(OaDOrder.VERSION, oaDOrders.get(0).getVersion() + 1);
                    dOrderUpdate.eq(OaDOrder.ORDER_NO, orderNo);
                    dOrderUpdate.eq(OaDOrder.VERSION, oaDOrders.get(0).getVersion());
                    try {
                        int dUpdate = oaDOrderMapper.update(null, dOrderUpdate);
                        if (dUpdate < 1) {
                            throw DiDiException.create(EDiDiErrorCode.dOrderUpdateFail);
                        }
                    } catch (Exception e) {
                        throw DiDiException.create(EDiDiErrorCode.dOrderUpdateFail);
                    }
                    QueryWrapper<OaDUserInfo> dUserWrapper = new QueryWrapper<>();
                    dUserWrapper.select(OaDUserInfo.CURRENT_ORDER_NO);
                    dUserWrapper.eq(OaDUserInfo.DRIVER_ID, oaCOrderPersonal.getDriverId());
                    OaDUserInfo one = dUserInfoService.getOne(dUserWrapper);
                    if (StringUtils.equals(one.getCurrentOrderNo(), orderNo)) {
                        // 释放司机运力
                        iMqService.driverUnlock(oaCOrderPersonal.getDriverId().toString());
                    }
                }
                return DiDiRv.wrap(EDiDiErrorCode.success, results);
            }
            try {
                return JSONObject.parseObject(data, DiDiRv.class);
            } catch (Exception e) {
                throw DiDiException.create(EDiDiErrorCode.DiDiGrabServerError);
            }
        } else {
            // 判断司机状态（行程中，待发起收款）14/19
            if (EOrderStatus.sendBill.getType().equals(oaCOrderPersonal.getOrderStatus()) || EOrderStatus.servicceItineraryClose.getType().equals(oaCOrderPersonal.getOrderStatus())) {
                log.info("客服关单，我是待发起收款的关单，订单号为：{}", orderNo);
                InitiatePaymentParam initiatePaymentParam = new InitiatePaymentParam();
                initiatePaymentParam.setOrderNo(orderNo);
                initiatePaymentParam.setIsCloseOrder(true);
                iMqService.initiatePayment(initiatePaymentParam);
            } else {
                log.info("客服关单，我是行程中的关单，我的状态为：{}，我改动的状态位：{}，订单号为：{}", oaCOrderPersonal.getOrderStatus(), EOrderStatus.servicceItineraryClose.getType(), orderNo);
                // 跨服务调用order
                OrderArrivalsParam orderArrivalsParam = new OrderArrivalsParam();
                orderArrivalsParam.setOrderNo(orderNo);
                orderArrivalsParam.setActualEndName("");
                orderArrivalsParam.setActualTlng("");
                orderArrivalsParam.setActualTlat("");
                orderArrivalsParam.setOrderStatus(EOrderStatus.servicceItineraryClose.getType());
                // 逆地理编码
                if (CheckUtil.objIsNotEmpty(oaDVehicleGps)) {
                    String regeo = iAmapService.getRegeo(oaDVehicleGps.getLng() + "," + oaDVehicleGps.getLat());
                    regeo = regeo.replaceAll("\"", "");
                    orderArrivalsParam.setActualEndName(regeo);
                    orderArrivalsParam.setActualTlng(oaDVehicleGps.getLng());
                    orderArrivalsParam.setActualTlat(oaDVehicleGps.getLat());
                }
                iMqService.endTakingPassengers(orderArrivalsParam);
            }
            return DiDiRv.wrapSuccess(new Object());
        }
    }

    /**
     * 直接调用滴滴客服关单（异常情况处理）
     *
     * @param param
     * @return
     */
    @Override
    public DiDiRv getCloseOrderDidiError(CloseOrderParam param) {
        String url = DiDiUrlConstant.didiUrl + DiDiUrlConstant.CLOSE_ORDER_API;
        param.setApp_id(DiDiUrlConstant.didiAppId);
        param.setSign(DiDiUrlConstant.didiSignPro);
        Date date = new Date();
        String timestamp = String.valueOf(date.getTime() / 1000);
        param.setTimestamp(timestamp);
        String signParameter = AttestationTool.getSign(param, DiDiUrlConstant.X_WWW_FORM_URLENCODED);
        String data = null;
        try {
            data = RetryUtil.retryRequestMethodUtil(signParameter, url, null, null, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (CheckUtil.strIsEmpty(data)) {
            throw DiDiException.create(EDiDiErrorCode.httpRequestDidiUrlError);
        }
        return DiDiRv.wrapSuccess(data);
    }

    @Override
    public DiDiRv getCloseOrder2(CloseOrderParam closeOrderParam) {
        return null;
    }

    /**
     * 改价
     *
     * @param param 入参实体
     * @return
     */
    @Override
    public DiDiRv getChangePrice(ChangePriceParam param) {
        String orderNo = param.getOrder_id();
        if (StringUtils.isBlank(param.getOperator_name()) || StringUtils.isBlank(orderNo) || StringUtils.isBlank(param.getOpen_oid())) {
            return DiDiRv.wrapError(EDiDiErrorCode.parameterError);
        }
        String is_affect_account = param.getIs_affect_account();
        param.setUserToken(null);
        param.setWorksheetId(null);
        param.setIs_affect_account(null);
        String url = DiDiUrlConstant.didiUrl + DiDiUrlConstant.CHANGE_PRICE_API;
        param.setSign(DiDiUrlConstant.didiSignPro);
        Date date = new Date();
        String timestamp = String.valueOf(date.getTime() / 1000);
        param.setTimestamp(timestamp);
        param.setApp_id(DiDiUrlConstant.didiAppId);
        log.info("DIDI改价: 账单详情: {}", param.getPassenger_bill());
        String signParameter = AttestationTool.getSign(param, DiDiUrlConstant.X_WWW_FORM_URLENCODED);
        String data = null;
        try {
            data = RetryUtil.retryRequestMethodUtil(signParameter, url, null, null, null);
        } catch (Exception e) {
            log.error("调用滴滴接口失败" + e.getMessage());
            throw DiDiException.create(EDiDiErrorCode.priceRevisionError);
        }
        log.info("DIDI改价: 返回值: {}", data);
        if (CheckUtil.strIsEmpty(data)) {
            throw DiDiException.create(EDiDiErrorCode.httpRequestDidiUrlError);
        }
        JSONObject jsonObject = JSONObject.parseObject(data);
        if (jsonObject.get(DiDiUrlConstant.ERRNO).equals(EDiDiErrorCode.success.getValue())) {
            PassengerBill passenger_bill = param.getPassenger_bill();
            OaCOrderPersonal oaCOrderPersonal = oaCOrderPersonalMapper.selectOne(Qw.create().eq(OaCOrderPersonal.ORDER_NO, orderNo));
            OaSysMessage oaSysMessage = new OaSysMessage();
            oaSysMessage.setMessageType(1);
            oaSysMessage.setPushCode(EBillType.ITINERARY_FARE.getIdenifition());
            oaSysMessage.setMessageContent(MessageConstant.CHANGE_PRICE);
            oaSysMessage.setDriverId(oaCOrderPersonal.getDriverId());
            oaSysMessage.setTag(oaCOrderPersonal.getTag());
            feignMessageService.saveMessage(oaSysMessage);
            oaCOrderPersonal.setIsChangePrice(1);
            return updateOrder(passenger_bill, oaCOrderPersonal, EUpdateOrderType.changePrice, is_affect_account);
        } else {
            return DiDiRv.wrap(jsonObject.getInteger(DiDiUrlConstant.ERRNO), jsonObject.getString(DiDiUrlConstant.ERRMSG));
        }

    }

    /**
     * 退款接口
     *
     * @param param 入参实体
     * @return
     */
    @Override
    public DiDiRv getBillRefund(BillRefundParam param) {
        String orderNo = param.getOrder_id();
        if (StringUtils.isBlank(param.getRefund_cost()) || StringUtils.isBlank(orderNo) || StringUtils.isBlank(param.getOpen_oid())) {
            return DiDiRv.wrapError(EDiDiErrorCode.parameterError);
        }
        //获取账单数据,因为需要使用但不能参数验签,所以值为空
        String serialNumber = OrderUtil.orderNo(EOrderType.REFUND);
        param.setRefund_id(serialNumber);//流水号

        PassengerBill passenger_bill = param.getPassenger_bill();
        String is_affect_account = param.getIs_affect_account();
        param.setPassenger_bill(null);
        param.setIs_affect_account(null);

        //调用滴滴退款接口
        String data = this.refundDidiOrder(param);
        if (CheckUtil.strIsEmpty(data)) {
            throw DiDiException.create(EDiDiErrorCode.httpRequestDidiUrlError);
        }
        JSONObject jsonObject = JSONObject.parseObject(data);
        if (jsonObject.get(DiDiUrlConstant.ERRNO).equals(EDiDiErrorCode.success.getValue())) {
            // 获取订单信息
            OaCOrderPersonal oaCOrderPersonal = oaCOrderPersonalMapper.selectOne(Qw.create().eq(OaCOrderPersonal.ORDER_NO, orderNo));
            oaCOrderPersonal.setIsRefund(1);
            return updateOrder(passenger_bill, oaCOrderPersonal, EUpdateOrderType.refund, is_affect_account);
        }
        return DiDiRv.wrap(jsonObject.getInteger(DiDiUrlConstant.ERRNO), jsonObject.getString(DiDiUrlConstant.ERRMSG));
    }

    /**
     * 获取订单金额改变差值
     *
     * @param originlValue 原金额
     * @param diffValue    修改后金额
     * @param orderNo      订单号
     * @param orderFeeType 订单费用类型
     * @param orderType    修改类型( 0 - 改价 1 - 退款)
     * @return
     */
    public BigDecimal subtractDiff(BigDecimal originlValue, BigDecimal diffValue,
                                   String orderNo, EUpdateOrderFeeType orderFeeType,
                                   EUpdateOrderType orderType, String serialNumber) {
        //退款,如果是改价不需要这一步操作
        if (orderType.equals(EUpdateOrderType.refund)) {
            if (CheckUtil.objIsEmpty(originlValue)) {
                originlValue = diffValue;
            }
            //
            diffValue = originlValue.subtract(diffValue);
        }

        long tokenUserId = 1L;
        Date date = new Date();
        //添加修改记录,暂无后面补充
        OaOrderFeeRecord oaOrderFeeRecord = new OaOrderFeeRecord();
        oaOrderFeeRecord.setRecordId(IDUtil.nextId());
        oaOrderFeeRecord.setCreateTime(date);
        oaOrderFeeRecord.setCreateUser(tokenUserId);
        oaOrderFeeRecord.setUpdateTime(date);
        oaOrderFeeRecord.setFeeType(orderFeeType.getType());
        oaOrderFeeRecord.setOrderNo(orderNo);
        oaOrderFeeRecord.setUpdateType(orderType.getType());
        oaOrderFeeRecord.setUpdateUser(tokenUserId);
        oaOrderFeeRecord.setOriginlFee(originlValue);
        oaOrderFeeRecord.setDiffFee(diffValue);
        oaOrderFeeRecord.setSerialNumber(serialNumber);
        oaOrderFeeRecordMapper.insert(oaOrderFeeRecord);
        return diffValue;
    }

    /**
     * 更改订单信息,并且生成流水
     *
     * @param passenger_bill   账单
     * @param oaCOrderPersonal 订单
     * @return
     */
    public DiDiRv updateOrder(PassengerBill passenger_bill, OaCOrderPersonal oaCOrderPersonal, EUpdateOrderType orderType, String is_affect_account) {
        String orderNo = oaCOrderPersonal.getOrderNo();
        //判断redis中是否存在
        if (CheckUtil.objIsEmpty(oaCOrderPersonal)) {
            throw DiDiException.create(EDiDiErrorCode.orderFlow);
        }
        //获取修改后的总金额
        BigDecimal totalFee = this.subtractDiff(oaCOrderPersonal.getTotalFee(), passenger_bill.getTotal_fee(),
                orderNo, EUpdateOrderFeeType.totalFee, orderType, "");
        oaCOrderPersonal.setTotalFee(totalFee);
        //获取修改后的里程费
        BigDecimal mileageFee = this.subtractDiff(oaCOrderPersonal.getMileageFee(), passenger_bill.getNormal_fee(),
                orderNo, EUpdateOrderFeeType.mileageFee, orderType, "");
        oaCOrderPersonal.setMileageFee(mileageFee);
        //获取修改后的远途费
        BigDecimal distanceFee = this.subtractDiff(oaCOrderPersonal.getDistanceFee(), passenger_bill.getEmpty_fee(),
                orderNo, EUpdateOrderFeeType.distanceFee, orderType, "");
        oaCOrderPersonal.setDistanceFee(distanceFee);
        //获取修改后的起步价
        BigDecimal startFee = this.subtractDiff(oaCOrderPersonal.getStartFee(), passenger_bill.getStart_fee(),
                orderNo, EUpdateOrderFeeType.startFee, orderType, "");
        oaCOrderPersonal.setStartFee(startFee);
        //获取修改后的时长
        BigDecimal durationFee = this.subtractDiff(oaCOrderPersonal.getDurationFee(), passenger_bill.getTime_fee(),
                orderNo, EUpdateOrderFeeType.timeFee, orderType, "");
        oaCOrderPersonal.setDurationFee(durationFee);
        //获取需要抽成的费用总金额
        BigDecimal needDrawFee = mileageFee.add(startFee).add(distanceFee).add(durationFee);
        //更新其他费用
        BigDecimal highway_fee = new BigDecimal("0");
        BigDecimal bridge_fee = new BigDecimal("0");
        BigDecimal park_fee = new BigDecimal("0");
        List<OaOrderOtherPrice> oaOrderOtherPrices = iMqService.queryOrderOtherPrice(orderNo);
        if (CheckUtil.collectionIsNotEmpty(oaOrderOtherPrices)) {
            List<OaOrderOtherPrice> updateOtherPrices = new ArrayList<>();
            if (CheckUtil.collectionIsNotEmpty(oaOrderOtherPrices)) {
                for (OaOrderOtherPrice oaOrderOtherPrice : oaOrderOtherPrices) {
                    BigDecimal costAmount = oaOrderOtherPrice.getCostAmount();
                    //高速费
                    if (oaOrderOtherPrice.getCostType().equals(EOrderOtherPrice.highSpeedFee.getType())) {
                        highway_fee = this.subtractDiff(costAmount, passenger_bill.getHighway_fee(),
                                orderNo, EUpdateOrderFeeType.highSpeedFee, orderType, "");
                        oaOrderOtherPrice.setCostAmount(highway_fee);
                    }
                    //过桥费
                    else if (oaOrderOtherPrice.getCostType().equals(EOrderOtherPrice.bridgeToll.getType())) {
                        bridge_fee = this.subtractDiff(costAmount, passenger_bill.getBridge_fee(),
                                orderNo, EUpdateOrderFeeType.bridgeFee, orderType, "");
                        oaOrderOtherPrice.setCostAmount(bridge_fee);
                    }
                    //停车费
                    else if (oaOrderOtherPrice.getCostType().equals(EOrderOtherPrice.parkingFee.getType())) {
                        park_fee = this.subtractDiff(costAmount, passenger_bill.getPark_fee(),
                                orderNo, EUpdateOrderFeeType.parkingFee, orderType, "");
                        oaOrderOtherPrice.setCostAmount(park_fee);
                    }
                    updateOtherPrices.add(oaOrderOtherPrice);
                }
            }
            if (!iMqService.updateOrderOtherPrice(updateOtherPrices)) {
                log.info("更新其他费用失败");
            }
        } else {
            log.info("为获取到其他费用!");
        }

        //设置抽成费
        OaSysBillRules oaSysBillRules = billRulesMapper.selectById(oaCOrderPersonal.getRulesId());
        //原司机抽成后费用
        BigDecimal drawFeeOld = oaCOrderPersonal.getDrawFee();
        if (CheckUtil.objIsNotEmpty(oaSysBillRules)) {
            //对总金额进行抽成
            BigDecimal drawRatio = oaSysBillRules.getDrawRatio();
            //获取抽成以后的费用
            needDrawFee = needDrawFee.subtract(needDrawFee.multiply(drawRatio)).setScale(2, BigDecimal.ROUND_UP);
            //添加上不需要抽成的费用
            drawFeeOld = needDrawFee.add(highway_fee.add(bridge_fee).add(park_fee));
        } else {
            drawFeeOld = totalFee;
        }
        // 判断是否影响司机流水,如果不为空并且等于1则影响司机流水
        if (CheckUtil.objIsNotEmpty(is_affect_account) && is_affect_account.equals("1")) {
            oaCOrderPersonal.setDrawFee(drawFeeOld);
            //修改司机冻结金额
            oaDFreezeService.updateFreezeBalance(orderNo, oaCOrderPersonal.getDriverId(), oaCOrderPersonal.getDrawFee());
            BigDecimal drawFeeNew = oaCOrderPersonal.getDrawFee().subtract(drawFeeOld);
            if (drawFeeNew.compareTo(BigDecimal.ZERO) != 0) {
                this.saveOaDBill(orderNo, drawFeeNew, oaCOrderPersonal.getDriverId());
            }
        }
        if (oaCOrderPersonalMapper.updateById(oaCOrderPersonal) <= 0) {
            log.info("ORDER_HISTORY 订单号:[{}],改价,更改订单失败!", orderNo);
            DiDiException.create(EDiDiErrorCode.orderPersonalUpdateFail);
        }
        return DiDiRv.wrapSuccess(new Object());
    }

    /**
     * 免单计算金额
     *
     * @param oaCOrderPersonal 订单
     * @return
     */
    public void updateOrderFreeCharge(OaCOrderPersonal oaCOrderPersonal, UpdateWrapper<OaCOrderPersonal> updateWra) {
        String orderNo = oaCOrderPersonal.getOrderNo();

        if (CheckUtil.objIsEmpty(oaCOrderPersonal)) {
            throw DiDiException.create(EDiDiErrorCode.orderFlow);
        }
        //获取修改后的总金额
        BigDecimal totalFee = new BigDecimal(0);
        oaCOrderPersonal.setTotalFee(totalFee);
        updateWra.set(OaCOrderPersonal.TOTAL_FEE, totalFee);

        //获取修改后的里程费
        BigDecimal mileageFee = new BigDecimal(0);
        oaCOrderPersonal.setMileageFee(mileageFee);
        updateWra.set(OaCOrderPersonal.MILEAGE_FEE, mileageFee);

        //获取修改后的远途费
        BigDecimal distanceFee = new BigDecimal(0);
        oaCOrderPersonal.setDistanceFee(distanceFee);
        updateWra.set(OaCOrderPersonal.DISTANCE_FEE, distanceFee);

        //获取修改后的起步价
        BigDecimal startFee = new BigDecimal(0);
        oaCOrderPersonal.setStartFee(startFee);
        updateWra.set(OaCOrderPersonal.START_FEE, startFee);

        //获取修改后的时长
        BigDecimal durationFee = new BigDecimal(0);
        oaCOrderPersonal.setDurationFee(durationFee);
        updateWra.set(OaCOrderPersonal.DURATION_FEE, durationFee);

        //更新其他费用
        BigDecimal highway_fee = new BigDecimal("0");
        BigDecimal bridge_fee = new BigDecimal("0");
        BigDecimal park_fee = new BigDecimal("0");

        List<OaOrderOtherPrice> oaOrderOtherPrices = iMqService.queryOrderOtherPrice(orderNo);
        if (CheckUtil.collectionIsNotEmpty(oaOrderOtherPrices)) {
            List<OaOrderOtherPrice> updateOtherPrices = new ArrayList<>();
            if (CheckUtil.collectionIsNotEmpty(oaOrderOtherPrices)) {
                for (OaOrderOtherPrice oaOrderOtherPrice : oaOrderOtherPrices) {
                    BigDecimal costAmount = oaOrderOtherPrice.getCostAmount();
                    //高速费
                    if (oaOrderOtherPrice.getCostType().equals(EOrderOtherPrice.highSpeedFee.getType())) {
                        oaOrderOtherPrice.setCostAmount(highway_fee);
                    }
                    //过桥费
                    else if (oaOrderOtherPrice.getCostType().equals(EOrderOtherPrice.bridgeToll.getType())) {
                        oaOrderOtherPrice.setCostAmount(bridge_fee);
                    }
                    //停车费
                    else if (oaOrderOtherPrice.getCostType().equals(EOrderOtherPrice.parkingFee.getType())) {
                        oaOrderOtherPrice.setCostAmount(park_fee);
                    }
                    updateOtherPrices.add(oaOrderOtherPrice);
                }
            }
            if (!iMqService.updateOrderOtherPrice(updateOtherPrices)) {
                log.info("更新其他费用失败");
            }
        } else {
            log.info("为获取到其他费用!");
        }

        //原司机抽成后费用
        BigDecimal drawFeeOld = oaCOrderPersonal.getDrawFee();

        oaCOrderPersonal.setDrawFee(totalFee);
        updateWra.set(OaCOrderPersonal.TOTAL_FEE, totalFee);

        //修改司机冻结金额
        oaDFreezeService.updateFreezeBalance(orderNo, oaCOrderPersonal.getDriverId(), new BigDecimal("0"));
        //负流水
        this.saveOaDBill(orderNo, drawFeeOld.negate(), oaCOrderPersonal.getDriverId());
    }

    /**
     * 免单接口
     *
     * @param param 入参实体
     * @return
     */
    @Override
    public DiDiRv getFreeCharge(FreeChargeParam param) {
        if (StringUtils.isBlank(param.getDetail_content()) || StringUtils.isBlank(param.getOrder_id()) || StringUtils.isBlank(param.getOpen_oid())) {
            return DiDiRv.wrapError(EDiDiErrorCode.parameterError);
        }
        //免单处理方式。01=平台补贴 02=司机承担（司机无此单收入)
        String handleType = param.getHandleType();
        param.setHandleType(null);
        String url = DiDiUrlConstant.didiUrl + DiDiUrlConstant.FREE_CHARGE_API;
        param.setApp_id(DiDiUrlConstant.didiAppId);
        param.setSign(DiDiUrlConstant.didiSignPro);
        Date date = new Date();
        String timestamp = String.valueOf(date.getTime() / 1000);
        param.setTimestamp(timestamp);
        String signParameter = AttestationTool.getSign(param, DiDiUrlConstant.X_WWW_FORM_URLENCODED);
        String data = null;
        try {
            data = RetryUtil.retryRequestMethodUtil(signParameter, url, null, null, null);
        } catch (Exception e) {
            log.error("调用滴滴免单接口失败");
            throw DiDiException.create(EDiDiErrorCode.freeSheetError);
        }
        if (CheckUtil.strIsEmpty(data)) {
            throw DiDiException.create(EDiDiErrorCode.httpRequestDidiUrlError);
        }
        JSONObject jsonObject = JSONObject.parseObject(data);
        if (jsonObject.get(DiDiUrlConstant.ERRNO).equals(EDiDiErrorCode.success.getValue())) {
            // 成功，修改订单状态105已支付
            // 查找订单,客服只需要输入第三方订单号即可
            OaCOrderPersonal oaCOrderPersonal = oaCOrderPersonalMapper.selectOne(Qw.create().eq(OaCOrderPersonal.ORDER_NO, param.getOrder_id()));
            if (CheckUtil.objIsEmpty(oaCOrderPersonal)) {
                log.error("查询订单为空,免单操作居然成功了,不太理解? 订单号: {}", param.getOrder_id());
            }
            EDiDiOrderStatus byId = EDiDiOrderStatus.findByDidiType(105);
            // 修改订单表
            UpdateWrapper<OaCOrderPersonal> updateWra = new UpdateWrapper<>();
            updateWra.set(OaCOrderPersonal.VERSION, oaCOrderPersonal.getVersion() + 1);
            updateWra.set(OaCOrderPersonal.ORDER_STATUS, byId.getType());
            updateWra.set(OaCOrderPersonal.UPDATE_TIME, new Date());
            updateWra.set(OaCOrderPersonal.DIDI_ORDER_STATUS, byId.getDidiType());
            //加入where语句,否则更改全表状态
            updateWra.eq(OaCOrderPersonal.ORDER_NO, param.getOrder_id());
            updateWra.eq(OaCOrderPersonal.VERSION, oaCOrderPersonal.getVersion());
            //司机承担,扣除司机该订单的冻结金额
            if (handleType.equals(ParameterEnum.TWO.getTypeName())) {
                updateOrderFreeCharge(oaCOrderPersonal, updateWra);
            }
            int update = oaCOrderPersonalMapper.update(null, updateWra);
            if (update < 1) {
                throw DiDiException.create(EDiDiErrorCode.orderPersonalUpdateFail);
            }

            return JSONObject.parseObject(data, DiDiRv.class);
        }
        return DiDiRv.wrapSuccess(new Object());
    }


    /**
     * 退款查询接口
     *
     * @param param 入参实体
     * @return
     */
    @Override
    public DiDiRv getQueryRefund(OrderDetailParam param) {
        QueryRefundResults results = new QueryRefundResults();
        if (StringUtils.isBlank(param.getOrder_id()) || StringUtils.isBlank(param.getOpen_oid())) {
            return DiDiRv.wrap(EDiDiErrorCode.parameterError, results);
        }
        String url = DiDiUrlConstant.didiUrl + DiDiUrlConstant.QUERY_REFUND_API;
        param.setApp_id(DiDiUrlConstant.didiAppId);
        param.setSign(DiDiUrlConstant.didiSignPro);
        Date date = new Date();
        String timestamp = String.valueOf(date.getTime() / 1000);
        param.setTimestamp(timestamp);
        String signParameter = AttestationTool.getSign(param, DiDiUrlConstant.X_WWW_FORM_URLENCODED);
        String data = RequestMethodUtil.requestMethod(signParameter, url);
        if (CheckUtil.strIsEmpty(data)) {
            throw DiDiException.create(EDiDiErrorCode.httpRequestDidiUrlError);
        }
        JSONObject jsonObject = JSONObject.parseObject(data);
        if (jsonObject.get(DiDiUrlConstant.ERRNO).equals(EDiDiErrorCode.success.getValue())) {
            JSONObject dataObject = jsonObject.getJSONObject("data");
            if (CheckUtil.objIsNotEmpty(dataObject)) {
                results.setTrade_id(dataObject.getString("trade_id"));
                results.setRefund_id(dataObject.getString("refund_id"));
                results.setRefund_cost(dataObject.getString("refund_cost"));
                results.setRefund_detail(dataObject.getString("refund_detail"));
                results.setRefund_status(dataObject.getString("refund_status"));
                results.setRefund_time(dataObject.getString("refund_time"));
                results.setRemark(dataObject.getString("remark"));
            }
        }
        return DiDiRv.wrap(EDiDiErrorCode.success, results);
    }

    /**
     * 调用didi客服关单接口
     *
     * @param param
     * @return
     */
    private String closeDidiOrder(CloseOrderParam param) {
        String url = DiDiUrlConstant.didiUrl + DiDiUrlConstant.CLOSE_ORDER_API;
        param.setApp_id(DiDiUrlConstant.didiAppId);
        param.setSign(DiDiUrlConstant.didiSignPro);
        Date date = new Date();
        String timestamp = String.valueOf(date.getTime() / 1000);
        param.setTimestamp(timestamp);
        String signParameter = AttestationTool.getSign(param, DiDiUrlConstant.X_WWW_FORM_URLENCODED);
        String data = null;
        try {
            data = RetryUtil.retryRequestMethodUtil(signParameter, url, null, null, null);
        } catch (Exception e) {
            log.error("调用滴滴客服关单接口失败");
        }

        return data;
    }

    /**
     * 调用滴滴退款接口
     *
     * @param param
     * @return
     */
    private String refundDidiOrder(BillRefundParam param) {
        String url = DiDiUrlConstant.didiUrl + DiDiUrlConstant.BILL_REFUND_API;
        param.setApp_id(DiDiUrlConstant.didiAppId);
        param.setSign(DiDiUrlConstant.didiSignPro);
        Date date = new Date();
        String timestamp = String.valueOf(date.getTime() / 1000);
        param.setTimestamp(timestamp);
        log.info("DIDI退款: 账单详情: {}", param.getPassenger_bill());
        log.info("DIDI退款: 退款金额: {}", param.getRefund_cost());
        String signParameter = AttestationTool.getSign(param, DiDiUrlConstant.X_WWW_FORM_URLENCODED);
        String data = null;
        try {
            data = RetryUtil.retryRequestMethodUtil(signParameter, url, null, null, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info("DIDI退款: 返回值: {}", data);
        return data;
    }

    /**
     * 修改司机接单表
     *
     * @return
     */
    private int cancelUpdateDOrder(Date date, String orderId, Integer orderStatus) {
        // 修改司机接单表状态
        QueryWrapper<OaDOrder> dOrderQueryWrapper = new QueryWrapper<>();
        dOrderQueryWrapper.select(OaDOrder.VERSION);
        dOrderQueryWrapper.eq(OaDOrder.ORDER_NO, orderId);
        List<OaDOrder> oaDOrders = oaDOrderMapper.selectList(dOrderQueryWrapper);

        if (CheckUtil.collectionIsEmpty(oaDOrders)) {
            throw DiDiException.create(EDiDiErrorCode.dOrderSelectFail);
        }

        // 更新
        UpdateWrapper<OaDOrder> dOrderUpdateWrapper = new UpdateWrapper<>();
        dOrderUpdateWrapper.set(OaDOrder.UPDATE_TIME, date);
        dOrderUpdateWrapper.set(OaDOrder.VERSION, oaDOrders.get(0).getVersion() + 1);
        // 更新条件
        dOrderUpdateWrapper.eq(OaDOrder.ORDER_NO, orderId);
        dOrderUpdateWrapper.eq(OaDOrder.VERSION, oaDOrders.get(0).getVersion());

        if (-1 != orderStatus) {
            dOrderUpdateWrapper.set(OaDOrder.ORDER_STATUS, orderStatus);
        }

        try {
            int dUpdate = oaDOrderMapper.update(null, dOrderUpdateWrapper);
            if (dUpdate < 1) {
                throw DiDiException.create(EDiDiErrorCode.dOrderUpdateFail);
            } else {
                return dUpdate;
            }
        } catch (Exception e) {
            throw DiDiException.create(EDiDiErrorCode.dOrderUpdateFail);
        }
    }

    /**
     * 修改司机接单表
     *
     * @return
     */
    private int closeUpdateDOrder(UpdateWrapper<OaDOrder> dOrderUpdate, Date date, String orderId) {

        QueryWrapper<OaDOrder> dOrderQuery = new QueryWrapper<>();
        dOrderQuery.select(OaDOrder.VERSION);
        dOrderQuery.eq(OaDOrder.ORDER_NO, orderId);
        List<OaDOrder> oaDOrders = oaDOrderMapper.selectList(dOrderQuery);

        if (CheckUtil.collectionIsEmpty(oaDOrders)) {
            throw DiDiException.create(EDiDiErrorCode.dOrderSelectFail);
        }

        dOrderUpdate.set(OaDOrder.UPDATE_TIME, date);
        dOrderUpdate.set(OaDOrder.VERSION, oaDOrders.get(0).getVersion() + 1);
        dOrderUpdate.eq(OaDOrder.ORDER_NO, orderId);
        dOrderUpdate.eq(OaDOrder.VERSION, oaDOrders.get(0).getVersion());

        try {
            int dUpdate = oaDOrderMapper.update(null, dOrderUpdate);
            if (dUpdate < 1) {
                throw DiDiException.create(EDiDiErrorCode.dOrderUpdateFail);
            } else {
                return dUpdate;
            }
        } catch (Exception e) {
            throw DiDiException.create(EDiDiErrorCode.dOrderUpdateFail);
        }
    }

    /**
     * 修改订单表
     *
     * @param oaCOrderPersonal
     * @return
     */
    private int cancelUpdateOaCOrderPersonal(OaCOrderPersonal oaCOrderPersonal,
                                             Date date,
                                             String orderId,
                                             Integer orderStatus,
                                             Integer didiOrderStatus) {
        UpdateWrapper<OaCOrderPersonal> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set(OaCOrderPersonal.VERSION, oaCOrderPersonal.getVersion() + 1);
        updateWrapper.set(OaCOrderPersonal.ORDER_STATUS, orderStatus);
        updateWrapper.set(OaCOrderPersonal.DIDI_ORDER_STATUS, didiOrderStatus);
        updateWrapper.set(OaCOrderPersonal.UPDATE_TIME, date);
        updateWrapper.eq(OaCOrderPersonal.ORDER_NO, orderId);
        updateWrapper.eq(OaCOrderPersonal.VERSION, oaCOrderPersonal.getVersion());
        int update = oaCOrderPersonalMapper.update(null, updateWrapper);

        if (update < 1) {
            throw DiDiException.create(EDiDiErrorCode.orderPersonalUpdateFail);
        }

        return update;
    }


    /**
     * 修改订单表
     *
     * @param oaCOrderPersonal
     * @return
     */
    private int closeUpdateOaCOrderPersonal(UpdateWrapper<OaCOrderPersonal> updateWrapper,
                                            OaCOrderPersonal oaCOrderPersonal,
                                            Date date,
                                            String orderId,
                                            Integer orderStatus,
                                            Integer didiOrderStatus) {

        updateWrapper.set(OaCOrderPersonal.VERSION, oaCOrderPersonal.getVersion() + 1);
        updateWrapper.set(OaCOrderPersonal.ORDER_STATUS, orderStatus);
        updateWrapper.set(OaCOrderPersonal.DIDI_ORDER_STATUS, didiOrderStatus);
        updateWrapper.set(OaCOrderPersonal.UPDATE_TIME, date);
        updateWrapper.eq(OaCOrderPersonal.ORDER_NO, orderId);
        updateWrapper.eq(OaCOrderPersonal.VERSION, oaCOrderPersonal.getVersion());


        int update = oaCOrderPersonalMapper.update(null, updateWrapper);
        if (update < 1) {
            throw DiDiException.create(EDiDiErrorCode.orderPersonalUpdateFail);
        }

        return update;
    }

    /**
     * 创建司机账单流水
     *
     * @return
     */
    @Override
    public void saveOaDBill(String orderNo, BigDecimal drawFee, Long driverId) {
        try {
            Integer billType = 0;
            String billTypeDesc = "";

            int compare = drawFee.compareTo(BigDecimal.ZERO);
            if (compare > 0) {
                billType = BillConstant.INCOME;
                billTypeDesc = BillConstant.COMPENSATE;
            } else if (compare < 0) {
                billType = BillConstant.EXPAND;
                billTypeDesc = BillConstant.refund;

                //负数创建正数流水、通过状态判断正负流水
                drawFee = drawFee.negate();
            } else {
                return;
            }

            OaDBill oaDBill = new OaDBill();
            oaDBill.setDriverId(driverId);
            oaDBill.setOrderNumber(orderNo);
            oaDBill.setBillAmount(drawFee);
            oaDBill.setBillType(billType);
            oaDBill.setBillTypeDesc(billTypeDesc);
            oaDBill.setLogonTag(BillConstant.LogonTag);
            oaDBill.setTag(TokenUtil.getTag());

            oaDFreezeService.saveDriverBill(oaDBill);
        } catch (Exception ex) {
            log.info("创建司机流水失败");
        }
    }
}
